package com.atguigu.eduService.service.impl;

import com.atguigu.eduService.entity.EduChapter;
import com.atguigu.eduService.entity.EduVideo;
import com.atguigu.eduService.mapper.EduChapterMapper;
import com.atguigu.eduService.mapper.EduVideoMapper;
import com.atguigu.eduService.service.EduChapterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Chen Wen bo
 * @since 2021-07-22
 */
@Service
@Transactional
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Resource
    private EduChapterMapper eduChapterMapper;
    @Resource
    private EduVideoMapper eduVideoMapper;

    //课程大纲查询
    @Override
    public List<EduChapter> getChapterVideo(String courseId) {
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",courseId);
        chapterQueryWrapper.orderByAsc("sort");
        List<EduChapter> eduChapterList = eduChapterMapper.selectList(chapterQueryWrapper);
        eduChapterList.forEach(e->{
            QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
            wrapper.eq("chapter_id",e.getId());
            wrapper.orderByAsc("sort");
            List<EduVideo> eduVideoList = eduVideoMapper.selectList(wrapper);
            e.setChildren(eduVideoList);
        });
        return eduChapterList;
    }

    //添加章节
    @Override
    public void addChapter(EduChapter eduChapter) {
        eduChapterMapper.insert(eduChapter);
    }

    //修改章节
    @Override
    public void updateChapter(EduChapter eduChapter) {
        eduChapterMapper.updateById(eduChapter);
    }

    //根据章节id查询
    @Override
    public EduChapter getChapterInfo(String chapterId) {
        return eduChapterMapper.selectById(chapterId);
    }

    //删除章节
    @Override
    public void deleteChapter(String chapterId) {
        //根据chapterId查询小节表。如有，则不删除。
        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();
        eduVideoQueryWrapper.eq("chapter_id",chapterId);
        Integer count = eduVideoMapper.selectCount(eduVideoQueryWrapper);
        if (count > 0) {
            throw new RuntimeException();
        }
        eduChapterMapper.deleteById(chapterId);
    }
}
